import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import User from '../views/User.vue'
import Roles from '../views/Roles.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    children: [
      { path: '/home', redirect: '/welcome' },
      { path: '/welcome', component: Welcome },
      { path: '/users', component: User },
      { path: '/roles', component: Roles }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const token = window.sessionStorage.getItem('login_token')
  if (!token) return next('/login')
  next()
})

// router.afterEach((to, from) => {
//   // 可以在路由配置对象中获取匹配的组件实例
//   setTimeout(() => {
//     if (to.matched[0].path === '/home') {
//       to.matched[0].instances.default.activePath = to.path
//     }
//     window.sessionStorage.setItem('activePath', to.path)
//   }, 0)
// })

export default router
